<template>
  <div class="permission-strategy section-container">
    <div class="section-title">{{ pageTitle }}</div>
    <el-tabs v-model="activeTab" @tab-change="tabChange">
      <el-tab-pane label="权限策略" name="strategy"></el-tab-pane>
      <el-tab-pane label="权限管理" name="auth"></el-tab-pane>
    </el-tabs>
    <div class="section-actions">
      <div class="actions-left">
        <el-button v-if="activeTab === 'strategy'" v-permission="['setting:permission:strategy:add']" type="primary"
          @click="addStrategy">添加策略</el-button>
        <el-button v-else v-permission="['setting:permission:strategy:authAdd']" type="primary"
          @click="handleAdd">添加权限</el-button>
          <SearchCmp v-if="searchCmpArray.length" ref="searchCmpRef" :searchCmpArray="searchCmpArray" :searchForm="queryData" @onSubmit="getTableData" />
      </div>
    </div>
    <RuifoxTable v-if="activeTab === 'strategy'" :loading="optionLoading" :default-index="true" v-model:tableData="strategyList"
      v-model:fieldList="strategyFieldList">
      <template #options="{ element }">
        <div class="table-td-option">
          <el-button v-permission="['setting:permission:strategy:edit']" type="primary" link
            @click="permissionManage(element)">权限配置</el-button>
          <el-button v-permission="['setting:permission:strategy:edit']" type="primary" link
            @click="editStrategy(element)">修改策略</el-button>
          <el-button v-permission="['setting:permission:strategy:delete']" type="primary" link
            @click="deleteStrategy(element)">删除策略</el-button>
        </div>
      </template>
    </RuifoxTable>
    <RuifoxTable v-else v-model:tableData="authTableData" v-model:fieldList="authFieldList" :loading="authTableLoading"
      :default-index="true">
      <template #options="{ element }">
        <div class="table-td-option">
          <el-button v-permission="['setting:permission:strategy:authEdit']" type="primary" size="small" link
            @click="handleEditAuth(element)">编辑</el-button>
          <el-button v-permission="['setting:permission:strategy:authDelete']" type="primary" size="small" link
            @click="handleDeleteAuth(element)">删除</el-button>
        </div>
      </template>
    </RuifoxTable>

    <!-- 策略相关的弹窗 -->
    <el-dialog v-model="isShowStrategyAdd" title="添加策略" class="add-strategy-box" width="600px">
      <div class="add-step1">
        <el-form :model="strategyForm" ref="addStrategyFormRef" :rules="strategyRules" label-width="100px"
          label-position="right">
          <el-form-item label="策略名称:" prop="name">
            <el-input v-model="strategyForm.name"></el-input>
          </el-form-item>
          <el-form-item label="策略描述:" prop="description">
            <el-input v-model="strategyForm.description" type="textarea" />
          </el-form-item>
        </el-form>
      </div>
      <div class="footer-btn-box">
        <div class="inner-footer">
          <div class="right-btn-box">
            <el-button type="primary" round @click="submitInsertResourceAuthGroup"
              :loading="addOptionLoading">确定</el-button>
            <el-button round @click="isShowStrategyAdd = false">取消</el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <el-dialog v-model="isShowStrategyEdit" title="修改策略" width="600px">
      <el-form :model="strategyForm" ref="editStrategyFormRef" :rules="strategyRules" label-width="100px"
        label-position="right">
        <el-form-item label="策略名称:" prop="name">
          <el-input v-model="strategyForm.name"></el-input>
        </el-form-item>
        <el-form-item label="策略描述:" prop="description">
          <el-input v-model="strategyForm.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitUpdateResourceAuthGroup(editStrategyFormRef)"
            :loading="addOptionLoading">确认</el-button>
          <el-button @click="isShowStrategyEdit = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <StrategySetting v-model:show="isShowCategory" :auth-list="authList" :resource-auth-group-id="strategyForm.id" />

    <!-- 权限相关的弹窗 -->
    <el-dialog v-model="authDialog" :title="authForm.id ? '编辑权限' : '添加权限'" width="500px" @close="resetAuthForm">
      <el-form ref="authFormRef" :model="authForm" :rules="authFormRules" label-width="60px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="authForm.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="方法" prop="title">
          <el-input v-model="authForm.title" placeholder="请输入方法"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="authDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitAuth">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { insertResourceAuthGroup, getResourceAuthGroupList, updateResourceAuthGroup, deleteResourceAuthGroup, getAuthList, insertAuth, updateAuth, deleteAuth } from '@/api/strategy'
import { ElMessage, ElMessageBox } from 'element-plus'
import StrategySetting from './components/StrategySetting.vue'

const router = useRouter()
const pageTitle = computed(() => router.currentRoute.value.meta.title)

const searchCmpRef = ref(null)
const searchCmpArray = ref([
  { label: '名称', key: 'name' },
])
const queryData = reactive({name: ''})
const getTableData = () => {
  if  (activeTab.value === 'strategy') {
    handleGetResourceAuthGroupList()
  } else {
    handleGetAuthList()
  }
}

// Tab相关
const activeTab = ref('strategy')
const tabChange = () => {
  searchCmpRef.value.clearForm(queryData)
  searchCmpRef.value.showTags()
  getTableData()
}

// 策略管理相关变量
const strategyList = ref([])
const optionLoading = ref(false)
const strategyFieldList = ref([
  {
    title: '策略名称',
    name: 'name',
    showTextTip: true
  },
  {
    title: '操作',
    width: 240,
    fixed: 'right',
    name: 'options'
  }
])

// 策略表单相关
const isShowStrategyAdd = ref(false)
const isShowStrategyEdit = ref(false)
const addOptionLoading = ref(false)
const addStrategyFormRef = ref()
const editStrategyFormRef = ref()
const defaultStrategyForm = {
  name: '',
  description: ''
}
const strategyForm = reactive(Object.assign({}, defaultStrategyForm))
const strategyRules = {
  name: [{ required: true, trigger: 'blur', message: '请填写策略名称' }]
}

// 权限管理相关变量
const authTableData = ref([])
const authTableLoading = ref(false)
const authFieldList = ref([
  { title: '名称', name: 'name', showTextTip: true },
  { title: '方法', name: 'title' },
  { title: '操作', width: '150px', name: 'options', fixed: 'right' }
])

// 权限表单相关
const authDialog = ref(false)
const authFormRef = ref(null)
const defaultAuthForm = reactive({
  name: '',
  title: ''
})
const authForm = ref(Object.assign({}, defaultAuthForm))
const authFormRules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  title: [{ required: true, message: '请输入方法', trigger: 'blur' }]
})

// 权限配置相关
const isShowCategory = ref(false)
const authList = ref([])

// 策略管理方法
const handleGetResourceAuthGroupList = async () => {
  optionLoading.value = true
  const res = await getResourceAuthGroupList(queryData)
  if (res.code === 20000) {
    strategyList.value = res.data
  }
  optionLoading.value = false
}

const addStrategy = () => {
  if (addStrategyFormRef.value) {
    addStrategyFormRef.value.resetFields()
  }
  Object.assign(strategyForm, defaultStrategyForm)
  isShowStrategyAdd.value = true
}

const submitInsertResourceAuthGroup = () => {
  addOptionLoading.value = true
  insertResourceAuthGroup(strategyForm)
    .then(res => {
      if (res.code === 20000) {
        handleGetResourceAuthGroupList()
        ElMessage.success('添加成功')
        addOptionLoading.value = false
        isShowStrategyAdd.value = false
      }
    })
    .catch(() => {
      addOptionLoading.value = false
      isShowStrategyAdd.value = false
    })
}

const editStrategy = data => {
  Object.assign(strategyForm, data)
  isShowStrategyEdit.value = true
}

const submitUpdateResourceAuthGroup = async formEl => {
  if (!formEl) return
  await formEl.validate(valid => {
    if (valid) {
      addOptionLoading.value = true
      updateResourceAuthGroup(strategyForm)
        .then(res => {
          if (res.code === 20000) {
            ElMessage.success('修改成功')
          }
          handleGetResourceAuthGroupList()
        })
        .finally(() => {
          isShowStrategyEdit.value = false
          addOptionLoading.value = false
        })
    }
  })
}

const deleteStrategy = data => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除该策略？</p><span style="font-size: 14px;color: #FF5240;">删除后将被移除</span></div>', '删除确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(() => {
    deleteResourceAuthGroup({ id: data.id }).then(() => {
      handleGetResourceAuthGroupList()
      ElMessage.success('删除成功')
    })
  })
}

// 权限管理方法
const handleGetAuthList = async () => {
  authTableLoading.value = true
  const res = await getAuthList(queryData)
  if (res.code === 20000) {
    authTableData.value = res.data
    authList.value = res.data
  }
  authTableLoading.value = false
}

const handleAdd = () => {
  authDialog.value = true
}

const handleEditAuth = data => {
  authForm.value = Object.assign({}, data)
  authDialog.value = true
}

const handleSubmitAuth = () => {
  authFormRef.value.validate(async valid => {
    if (valid) {
      let res
      if (authForm.value.id) {
        res = await updateAuth(authForm.value)
      } else {
        res = await insertAuth(authForm.value)
      }
      if (res.code === 20000) {
        const msg = authForm.value.id ? '修改成功' : '添加成功'
        ElMessage.success(msg)
        authDialog.value = false
        handleGetAuthList()
      }
    }
  })
}

const handleDeleteAuth = data => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除选中的权限？</p><span style="font-size: 14px;color: #FF5240;">删除后该权限将被移除</span></div>', '删除确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(() => {
    deleteAuth({ id: data.id }).then(res => {
      if (res.code === 20000) {
        ElMessage.success('删除成功')
        handleGetAuthList()
      }
    })
  })
}

const resetAuthForm = () => {
  authFormRef.value.resetFields()
  authForm.value = Object.assign({}, defaultAuthForm)
}

const permissionManage = (data) => {
  Object.assign(strategyForm, data)
  isShowCategory.value = true
}

// 初始化
onMounted(() => {
  handleGetResourceAuthGroupList()
})
</script>

<style lang="scss" scoped>
.permission-strategy {
  .menu-tree-box {
    .custom-tree-node {
      display: flex;
      width: 100%;

      .tree-node-label {
        min-width: 200px;
      }

      .el-checkbox-group {
        flex: 1;
        display: flex;
        justify-content: space-around;
      }
    }

    .inner-menu-tree-box {
      width: max-content;
      position: relative;
      min-width: 100%;
    }

    .tree-header {
      height: 40px;
      background-color: #f5f7fa;
      width: 100%;
      box-sizing: border-box;
      border: 1px solid #dcdfe6;
      padding-left: 46px;
      display: flex;
      align-items: center;

      span {
        flex-grow: 1;
        font-size: 14px;

        &.tree-header-btn {
          width: 100px;
          flex-grow: 0;
          text-align: center;
        }
      }
    }

    .tree-content {
      :deep(.el-tree-node__content) {
        border-bottom: 1px solid #dcdfe6;
        border-left: 1px solid #dcdfe6;
        border-right: 1px solid #dcdfe6;
        height: 48px;
      }

      :deep(.el-tree-node__label) {
        width: 100%;

        .custom-tree-node {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;

          .tree-node-label {
            flex-grow: 1;
          }

          .tree-node-btn {
            width: 100px;
            text-align: center;

            .icon-select {
              color: #2cbf77;
            }

            .icon-close-bold {
              color: #ff5240;
            }
          }
        }
      }
    }
  }

  .add-strategy-box {
    .footer-btn-box {
      padding: 40px 0 0;

      .inner-footer {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
}

.el-dialog {
  .my-header {
    .tips {
      color: #666;
    }
  }
}
</style>
